package edu.ccut.saturn.component.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import edu.ccut.saturn.component.IBundleWorkFlowInfo;
import edu.ccut.saturn.component.ILogger;
import edu.ccut.saturn.component.IWorkFlowInfo;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.component.SaturnLoggerManager;

public class SaturnBundleWorkFlowInfo implements IBundleWorkFlowInfo {

	private static final String LOGGER_KEY_LOAD_BUNDLE = SaturnLoggerManager.LOGGER_KEY_LOAD_BUNDLE;

	protected static ILogger logger = SaturnLoggerManager.getInstance()
			.getSaturnLogger(LOGGER_KEY_LOAD_BUNDLE);

	private String bundlesSymbolicName;

	private Map<String, IWorkFlowInfo> workFlowInfoMap;

	public SaturnBundleWorkFlowInfo(String bundlesSymbolicName) {
		this.bundlesSymbolicName = bundlesSymbolicName;
		workFlowInfoMap = new HashMap<String, IWorkFlowInfo>();
	}

	public void addWorkFlowInfo(IWorkFlowInfo workFlowInfo)
			throws SaturnComponentException {

		this.validateWorkFlowInfoKey(workFlowInfo);
		this.workFlowInfoMap.put(workFlowInfo.getFullKey(), workFlowInfo);

		logger.debug("add componentInfo \"" + workFlowInfo.getFullKey()
				+ "\" from " + this.bundlesSymbolicName + " bundle");
	}

	public void addWorkflowInfos(Collection<IWorkFlowInfo> workFloInfos)
			throws SaturnComponentException {

		if (workFloInfos != null) {

			for (IWorkFlowInfo workFlowInfo : workFloInfos) {
				validateWorkFlowInfoKey(workFlowInfo);
			}

			for (IWorkFlowInfo workFlowInfo : workFloInfos) {
				this.validateWorkFlowInfoKey(workFlowInfo);
			}
		}
	}

	public String getBundleSymbolicName() {
		return this.bundlesSymbolicName;
	}

	public IWorkFlowInfo getWorkFlowInfo(String fullKey) {
		return this.workFlowInfoMap.get(fullKey);
	}

	public Collection<IWorkFlowInfo> getWorkFlowInfos() {
		return this.workFlowInfoMap.values();
	}

	public Set<String> getWorkFlowKeys() {
		return this.workFlowInfoMap.keySet();
	}

	private void validateWorkFlowInfoKey(IWorkFlowInfo workFlowInfo)
			throws SaturnComponentException {

		if (workFlowInfo.getFullKey() == null) {
			logger
					.error("add workFlowInfo failed, because the workflowInfo key is null");

			throw new SaturnComponentException(
					"add workFlowInfo failed, because the workflowInfo key is null");
		}

		if (this.workFlowInfoMap.containsKey(workFlowInfo.getFullKey())) {
			logger
					.error("add workFlowInfo failed, because the workFlowInfo key ["
							+ workFlowInfo.getFullKey()
							+ "] is already existed");
			
			throw new SaturnComponentException(
					"add workFlowInfo failed, because the workFlowInfo key ["
							+ workFlowInfo.getFullKey()
							+ "] is already existed");
		}
	}
}
